<template>
  <div>
    <div>
      <el-dialog :visible.sync="dialogVisible" title="是否进入聊天室？">
        <span style="padding-right:5px;">您的昵称是:</span>
        <el-input class="nickname" v-model="nickname" type="text" disabled />
        <el-button style="margin-top:10px;" type="primary" @click="enter">进入</el-button>
      </el-dialog>

      <div class="web-im">
        <div class="header im-title">聊天室</div>
        <div class="content im-record" id="chatRecord">
          <div
            id="contentBox"
            :class="item.nickname == nickname?'li-my':'li-other'"
            v-for="(item,index) in messageList"
            :key="index"
          >
            <template>
              <div class="name-box">{{item.nickname}}({{item.date}})：</div>
              <span class="message-box">{{item.msg}}</span>
            </template>
          </div>
        </div>
        <div class="footer im-input">
          <el-input
            style="width:600px;"
            type="textarea"
            maxlength="100"
            show-word-limit
            v-model="msg"
            placeholder="请输入聊天内容"
          />
          <el-button @click="send">发送</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      uid: "",
      nickname: "",
      // 连接websocket
      socket: "",
      msg: "",
      userClass: "",
      dialogVisible: true,
      messageList: []
    };
  },
  computed: {
    ...mapGetters(["name", "avatar", "roles", "token"])
  },
  mounted() {
    let vm = this;
    let name = vm.name || {};
    vm.nickname = name;
    // if (!vm.name) {
    //   vm.dialogVisible = true;
    // } else {
    //   vm.conWebSocket();
    // }
    document.onkeydown = function(event) {
      var e = event || window.event;
      if (e && e.keyCode == 13) {
        //回车键的键值为13
        vm.send();
      }
    };

    // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = this.onbeforeunload;
  },
  methods: {
    send() {
      if (!this.msg) {
        return;
      }
      this.sendMessage(2, this.msg);
    },
    sendMessage(type, msg) {
      this.socket.send(
        JSON.stringify({
          type: type,
          nickname: this.nickname,
          msg: msg
        })
      );
      this.msg = "";
    },
    conWebSocket() {
      if (window.WebSocket) {
        const uri = process.env.VUE_APP_WEBSOCKET_API;
        this.socket = new WebSocket(`${uri}/chatRoom/chat`);
        let socket = this.socket;
        let t = this;
        socket.onopen = function(e) {
          t.$message.success("连接成功");
        };
        socket.onclose = function(e) {
          t.$message.success("连接关闭");
        };
        socket.onerror = function() {
          t.$message.success("连接出错");
        };
        // 接收服务器的消息
        socket.onmessage = function(e) {
          let message = JSON.parse(e.data);
          t.messageList.push(message);
          t.$nextTick(() => {
            const block = document.getElementById("chatRecord"); // 获取对象
            block.scrollTop = block.scrollHeight; // 滚动高度
          });
        };
      } else {
        this.$message.error("当前浏览器不支持websocket");
      }
    },
    enter() {
      this.dialogVisible = false;
      this.conWebSocket();
    },
    onbeforeunload() {
      this.closeWebSocket();
    },
    closeWebSocket() {
      this.websocket.close();
    }
  }
};
</script>

<style lang='scss' scope>
.web-im {
  .content {
    background-color: rgba($color: #f1efef, $alpha: 1);
    height: 500px;
    overflow: auto;
    .li-other {
      text-align: left;
      padding-left: 10px;
      margin-bottom: 5px;
      .name-box {
        margin-bottom: 5px;
      }
      .message-box {
        font-size: 15px;
        padding: 0 5px;
        border-radius: 3px;
      }
    }
    .li-my {
      text-align: right;
      padding-right: 10px;
      margin-bottom: 5px;
      .name-box {
        margin-bottom: 5px;
      }
      .message-box {
        font-size: 15px;
        padding: 0 5px;
        border-radius: 3px;
        background-color: rgba($color: #c8dce9, $alpha: 1);
      }
    }
  }
  .header {
    text-align: center;
    font-size: 20px;
    margin-bottom: 20px;
  }
  .footer {
    margin-top: 20px;
    padding-left: 10px;
    .el-button {
      margin-left: 10px;
    }
  }
}
</style>